﻿using System;
using System.Data;
using System.Web.UI;
using MyWeb.Business;
using MyWeb.Common;

namespace MyWeb.TrangChinh.UC
{
    public partial class ucMyProfile : UserControl
    {
        private readonly UserService _userService = new UserService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["user_id"] != null)
                {
                    int id = Int32.Parse(Session["user_id"].ToString());
                    DataTable dUser = _userService.User_GetById(id);
                    txtName.Text = dUser.Rows[0]["name"].ToString();
                    txtBirthday.Text = DateTime.Parse(dUser.Rows[0]["birthday"].ToString()).ToString("dd/MM/yyyy");
                    txtEmail.Text = dUser.Rows[0]["email"].ToString();
                    ddlGender.SelectedValue = dUser.Rows[0]["gender"].ToString();
                    txtAddress.Text = dUser.Rows[0]["address"].ToString();
                    txtPhone.Text = dUser.Rows[0]["phone"].ToString();
                }
            }
        }

        protected void btnChange_Click(object sender, EventArgs e)
        {
            if (btnChange.Text == "Cập nhật")
            {
                txtPassWord.Enabled = true;
                txtPassWord.Focus();
                txtPassWordNew.Enabled = true;
                txtRePassWordNew.Enabled = true;
                btnChange.Text = "Hoàn tất";
            }
            else
            {
                DataTable dt = _userService.User_CheckLogin(Session["username"].ToString(),
                                                            StringClass.Encode("sha256", txtPassWord.Text.Trim()));
                if (dt.Rows.Count > 0)
                {
                    try
                    {
                        _userService.User_PasswordChange(Session["username"].ToString(),
                                                         StringClass.Encode("sha256", txtPassWord.Text.Trim()),
                                                         txtPassWordNew.Text.Trim());
                        WebMsgBox.Show("Đổi mật khẩu thành công!");
                    }
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    WebMsgBox.Show("Mật khẩu cũ không chính xác");
                }
            }
        }
    }
}